package com.htd.base.common.config;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Aspect
@Component
@Order(1)
@Slf4j
public class DataSourceAspect {
    @Autowired
    private LsCoreProperties lsCoreProperties;

    @Pointcut("execution(* com.htd.base.modules.translate.dao..*.*(..))")
    public void dataSourcePointcut() {
    }

    @Before("dataSourcePointcut()")
    public void before(JoinPoint point) {
        if (lsCoreProperties.getBase().language().getOpen()) {
            // 从请求上下文中获取数据源信息
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                String currentDataSource = (String) requestAttributes.getAttribute("currentDataSource", RequestAttributes.SCOPE_REQUEST);
                log.info("[Trans. plugin] Get datasource from request context: {}", currentDataSource);

                if (currentDataSource == null) {
                    // 如果请求上下文中没有，尝试从 ThreadLocal 获取
                    currentDataSource = DynamicDataSourceContextHolder.peek();
                    log.info("[Trans. plugin] Get datasource from ThreadLocal: {}", currentDataSource);

                    if (currentDataSource != null) {
                        // 保存到请求上下文中，供后续使用
                        requestAttributes.setAttribute("currentDataSource", currentDataSource, RequestAttributes.SCOPE_REQUEST);
                    }
                }
                // 切换到多语言数据源
                String languageDataSource = lsCoreProperties.getBase().language().database().getKey();
                log.info("[Trans. plugin] Switching to language datasource: {}", languageDataSource);
                DynamicDataSourceContextHolder.push(languageDataSource);
            } else {
                log.warn("[Trans. plugin] No request context available");
            }
        } else {
            log.debug("[Trans. plugin] 多語言資料庫功能未開啟");
        }
    }

    @After("dataSourcePointcut()")
    public void after(JoinPoint point) {
        if (lsCoreProperties.getBase().language().getOpen()) {
            // 从请求上下文中获取原始数据源
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                String originalDataSource = (String) requestAttributes.getAttribute("currentDataSource", RequestAttributes.SCOPE_REQUEST);
                if (originalDataSource != null) {
                    // 恢复原始数据源
                    DynamicDataSourceContextHolder.push(originalDataSource);
                    log.info("[Trans. plugin] Restored original datasource: {}", originalDataSource);
                }
            }
        } else {
            log.debug("[Trans. plugin] 多語言資料庫功能未開啟");
        }
    }
}
